package com.tyc.c09.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.CountDownLatch;

/**
 * JDK代理类需要实现某个接口
 */
public class JdkProxyDemo {
    interface Foo{
        void foo();
    }

    static class Target implements Foo{

        @Override
        public void foo() {
            System.out.println("foo");
        }
    }

    public static void main(String[] args) {
        // 用来加载在运行期间动态生成的字节码
        ClassLoader classLoader = JdkProxyDemo.class.getClassLoader();
        Foo o = (Foo) Proxy.newProxyInstance(classLoader, new Class[]{Foo.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("before ... ");
                // 目标方法调用
                Object result = method.invoke(new Target(),args);
                System.out.println("after ...");
                return result;
            }
        });
        System.out.println(o.getClass());
        o.foo();
        try {
            new CountDownLatch(1).await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
